import React, { Component } from 'react'
import Tab from './../components/common/TabVertical'
import Content from '../components/common/Content'
import Page from './../components/common/Page'
import Empty from './../components/common/Empty'
import styles from './HotNews.module.scss'
import api from './../serve/api'
import { withRouter } from 'react-router-dom'

class HotNews extends Component {

  constructor(props) {
    super(props)
    this.state = {
      types: [],
      news: [],
      typeId: '',
      pageTotal: '',
      page: 1,
      pageSize: 15,
      selected: 0
    }
  }
  
  onTab(item, index) {
    console.log(index)
    this.setState({
      selected: index,
      typeId: item.id
    })
    this.getHotNews(item.id, 1)
  }

  getCurrentPage(currentPage) {
    this.getHotNews(this.state.typeId, currentPage)
  }

  componentDidMount() {
    this.getHotNewsTypeAll()
  }

  async getHotNewsTypeAll() {
    const data = await api.fetchListHotNewsTypeAll()
    if (data && data.code === '000000') {
      this.setState({
        types: data.result
      })
      if (data.result.length > 0) {
        const first = data.result[0]
        this.getHotNews(first.id, this.state.page)
      }
    }
  }

  async getHotNews(typeId, page) {
    const data = await api.fetchListHotNews({ typeId, page, pageSize: this.state.pageSize })
    if (data && data.code === '000000') {
      this.setState({
        page,
        typeId,
        news: data.result || [],
        pageTotal: data.resultNum
      })
    }
  }

  onItem(item) {
    this.props.history.push(`/mainPage/commonDetail/hotNews/${item.id}`)
  }

  render() {
    const { types, news, page, pageTotal, selected } = this.state
    return (
      <div className={styles.hotNews_container}>
        <Tab tabs={types} selected={selected} onTab={(item, index) => this.onTab(item, index)} />
        <div className={styles.hotNews_content}>
          {news.length === 0 && <Empty title="暂无数据" />}
          {news.length > 0 && <Content datas={news} onItem={item => this.onItem(item)} />}
          {news.length > 0 && <Page 
            pageConfig={{totalPage: pageTotal, pageSize: this.state.pageSize, currentPage: page }}
            pageCallbackFn={currentPage => this.getCurrentPage(currentPage)}
          />}
        </div>
      </div>
    )
  }
}
export default withRouter(HotNews)
